package lyj.springcloud.sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.lyj.springcloud.entities.CommonResult;
import com.lyj.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试：
 *    当服务提供者发生熔断时，
 *    消费者什么情况
 *      :服务提供者发生熔断降级，执行对应降级方法，将对应的返回内容给到服务消费者
 *
 */
@RestController
public class ProviderSentinelController {


    @Value("${pro.name}")
    private String name;


    @Value("${dev.pro.name}")
    private String devName;



    @GetMapping("/getvalue")
    public CommonResult getValue() {
        return new CommonResult("application.yml：" + name + "application-dev.yml ：" + devName ) ;
    }

    @GetMapping(value = "/provider/sentinel/{id}")
    @SentinelResource(value = "providersentinel"
                       ,blockHandler = "providersentinel_blockHandler"
                       ,fallback = "providersentinel_fallback")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") String id){
        if ("1".equalsIgnoreCase(id)) {
            int i = 10 / 0 ;
        }
        return new CommonResult<>("ProviderSentinelController paymentSQL success");
    }


    /**
     * 超出sentinel规则配置，服务降级兜底返回方法
     * @param id 参数必须与原业务方法一致
     * @param blockException 必选项
     * @return
     */
    public CommonResult<Payment> providersentinel_blockHandler(String id , BlockException blockException){
        return new CommonResult<>("providersentinel_blockHandler 超出sentinel控制台规则配置，服务降级返回。");
    }


    /**
     * 业务异常降级兜底返回方法
     * @param id ：参数必须与原业务方法参数保持一致，原来有几个参数，降级方法必须也有多少个
     * @param throwable 可选项：可以获取异常信息
     * @return
     */
    public CommonResult<Payment> providersentinel_fallback(String id , Throwable throwable){
        return new CommonResult<>("服务异常，降级返回。异常信息：" + throwable.getMessage());
    }
}
